# -*- coding: utf-8 -*-
import paho.mqtt.client as mqtt
from openai import OpenAI
import json
import ssl
import time
import os


def get_response(messages):
    client = OpenAI(
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
    )
    completion = client.chat.completions.create(
        model="qwen-turbo-latest",
        #model="deepseek-r1-0528",
        messages=messages
    )
    return completion


messages = [{'role': 'system', 'content': '你是一个智慧农业决策者，会给你提供当前室内温度、湿度、风速、光照强度等数据，你要决策风扇是否启动，光照是否调整。'}, {
    'role': 'system', 'content': '数据输出格式：{"fanSpeed": 0, "led": 500}'}, {
    'role': 'system', 'content': '如果输入的格式不对，或者提问无关的内容，你不能回复其他的内容，直接回复：{"fanSpeed": 0, "led": 0}'}]

# 阿里云提供的MQTT参数
params = {
    "clientId": "k01baZKR6Hv.Mqtt_Py|securemode=2,signmethod=hmacsha256,timestamp=1749290620231|",
    "username": "Mqtt_Py&k01baZKR6Hv",
    "mqttHostUrl": "iot-06z00ay6q2ji2ib.mqtt.iothub.aliyuncs.com",
    "passwd": "51b000af64e075170caa7b0f9f091a9269e634b5337bc6ddf584908531b901cc",
    "port": 1883
}

# MQTT客户端连接回调函数


def on_connect(client, userdata, flags, rc, ew):
    print("Connected with result code " + str(rc))
    res = client.subscribe("/k01baZKR6Hv/Mqtt_Py/user/update")
    print("Subscribe result:", res)

# MQTT客户端消息接收回调函数


def publish_params(json_data):
    rc, mid = client.publish(
        "/k01baZKR6Hv/Mqtt_Py/user/get", json_data)
    if rc == 0:
        print("publish topic success:%r, mid:%r" % (rc, mid))
    else:
        print("publish topic fail:%d" % rc)


def on_message(client, userdata, msg):

    payload = msg.payload.decode('utf-8')
    json_data = json.loads(payload)
    params = json_data["params"]
    messages.append({'role': 'user', 'content': str(params)})
    assistant_output = get_response(messages).choices[0].message.content
    # 将大模型的回复信息添加到messages列表中
    messages.append({'role': 'assistant', 'content': assistant_output})

    print(f'模型输出：{assistant_output}')
    print("Received message: " + str(msg.payload))
    publish_params(assistant_output)



# 创建MQTT客户端实例
client = mqtt.Client(client_id=params["clientId"], protocol=mqtt.MQTTv5)

# 设置连接回调函数
client.on_connect = on_connect
client.on_message = on_message

# 设置TLS连接参数
client.tls_set(ca_certs=None, certfile=None, keyfile=None, cert_reqs=ssl.CERT_NONE, tls_version=ssl.PROTOCOL_TLS,
               ciphers=None)

# 设置用户名和密码
client.username_pw_set(params["username"], params["passwd"])


try:
    client.connect(params["mqttHostUrl"], params["port"], 60)
    print("MQTT连接", "已连接到MQTT服务器")
except Exception as e:
    print("MQTT连接错误", str(e))

client.loop_start()


# 断开与IoT平台的连接的函数


def disconnect_from_mqtt():
    try:
        client.disconnect()
        print("MQTT断开连接", "已断开与MQTT服务器的连接")
    except Exception as e:
        print("MQTT断开连接错误", str(e))




while True:
    time.sleep(1)
    # publish_params("{'temp': 25, 'hum': 60, 'light': 300, 'fanSpeed': 0, 'led': 500}")




